package ui.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;

import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;


import com.chad.library.adapter.base.BaseQuickAdapter;
import com.netease.neliveplayer.sdk.NEDefinitionData;
import com.netease.neliveplayer.sdk.NELivePlayer;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import adapter.PrePareTaskCoursewareAdapter;
import adapter.PrePareTaskWorkAdapter;
import base.BaseBean;
import base.activity.BaseNetActivity;
import bean.GetSubjectBean;
import bean.PrePareOrReViewDetailBean;
import receiver.Observer;
import receiver.PhoneCallStateObserver;
import service.PlayerService;
import student.andlei.com.student.R;
import utils.GsonUtils;
import utils.StringUtils;
import utils.TimerUtil;
import utils.log.LogUtil;
import view.MyLayoutManager;
import view.sdk.PlayerManager;
import view.sdk.VodPlayer;
import view.sdk.VodPlayerObserver;
import view.sdk.constant.CauseCode;
import view.sdk.model.MediaInfo;
import view.sdk.model.StateInfo;
import view.sdk.model.VideoBufferStrategy;
import view.sdk.model.VideoOptions;
import view.sdk.model.VideoScaleMode;
import view.sdk.view.AdvanceSingleTextureView;
import view.sdk.view.AdvanceSurfaceView;

/**
 *
 */
public class ReViewTaskActivity extends BaseNetActivity {
    //---------------播放器---------------
    private static final int SHOW_PROGRESS = 0x01;
    private ImageButton mPlayBack;
    private TextView mFileName; //文件名称
    private ImageView mAudioRemind; //播音频文件时提示
    private View mBuffer; //用于指示缓冲状态
    private RelativeLayout mPlayToolbar;
    private ImageView mPauseButton;
    private ImageView mSetPlayerScaleButton;
    private ImageView mSnapshotButton;
    private ImageView mMuteButton;
    private SeekBar mProgressBar;
    private TextView mEndTime;
    private TextView mCurrentTime;
    private AdvanceSurfaceView surfaceView;
    private AdvanceSingleTextureView textureView;
    private VodPlayer player;
    private MediaInfo mediaInfo;

    private String mVideoPath = ""; //文件路径
    private String mDecodeType = "software";//解码类型，硬解或软解
    private String mMediaType = "videoondemand"; //媒体类型
    private boolean mHardware = true;
    private Uri mUri;
    private String mTitle;
    private boolean mBackPressed;
    private boolean mPaused = false;
    private boolean isMute = false;
    private boolean mIsFullScreen = false;
    protected boolean isPauseInBackgroud;
    //----------------------------------------
    private TextView tv_subject,
            tv_teacher,
            tv_date_time_week;
    private RecyclerView rc_cours,
                       // rc_note,
                        rc_work;
    private List<PrePareOrReViewDetailBean.coursewareData> cours_list = new ArrayList();
    // private List<ItemBean> note_list = new ArrayList();
    private List<PrePareOrReViewDetailBean.taskData> work_list = new ArrayList();
    private PrePareTaskCoursewareAdapter coursewareAdapter;
    //private PrePareTaskNoteAdapter noteAdapter;
    private PrePareTaskWorkAdapter workAdapter;
    private int room_id;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseBack(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        setTitle("复习任务");
    }
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            long position;
            switch (msg.what) {
                case SHOW_PROGRESS:
                    position = setProgress();
                    msg = obtainMessage(SHOW_PROGRESS);
                    sendMessageDelayed(msg, 1000 - (position % 1000));
                    break;
            }
        }
    };
    private long setProgress() {
        if (player == null) {
            return 0;
        }
        int position = (int) player.getCurrentPosition();
        int duration = (int) player.getDuration();
        if (mProgressBar != null) {
            if (duration > 0) {
                LogUtil.i("", "setProgress,position:" + position + "duration:" + duration);
                long pos = 100L * position / duration;
                mProgressBar.setProgress((int) pos);
            }
        }

        if (mEndTime != null && duration > 0) {
            mEndTime.setText(TimerUtil.stringForTime(duration));
        } else {
            mEndTime.setText("--:--:--");
        }
        if (mCurrentTime != null) {
            mCurrentTime.setText(TimerUtil.stringForTime(position));
        }
        return position;
    }
    private View.OnClickListener mPlayBackOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mBackPressed = true;
            finish();
            releasePlayer();
        }
    };
    private void releasePlayer() {
        if (player == null) {
            return;
        }
        player.registerPlayerObserver(playerObserver, false);
        PhoneCallStateObserver.getInstance().observeLocalPhoneObserver(localPhoneObserver, false);
        player.setupRenderView(null, VideoScaleMode.NONE);
        textureView.releaseSurface();
        textureView = null;
        player.stop();
        player = null;
        intentToStopBackgroundPlay();
        mHandler.removeCallbacksAndMessages(null);
    }
    private void initPlayer() {
        VideoOptions options = new VideoOptions();
        options.autoSwitchDefinition = false;
        options.hardwareDecode = mHardware;
        /**
         * isPlayLongTimeBackground 控制退到后台或者锁屏时是否继续播放，开发者可根据实际情况灵活开发,我们的示例逻辑如下：
         * 使用软件解码：
         * isPlayLongTimeBackground 为 false 时，直播进入后台停止播放，进入前台重新拉流播放
         * isPlayLongTimeBackground 为 true 时，直播进入后台不做处理，继续播放,
         *
         * 使用硬件解码：
         * 直播进入后台停止播放，进入前台重新拉流播放
         */
        options.isPlayLongTimeBackground = !isPauseInBackgroud;
        options.bufferStrategy = VideoBufferStrategy.ANTI_JITTER;
        player = PlayerManager.buildVodPlayer(this, mVideoPath, options);
        //intentToStartBackgroundPlay();
        // start();
        if (surfaceView == null) {
            player.setupRenderView(textureView, VideoScaleMode.FIT);
        } else {
            player.setupRenderView(surfaceView, VideoScaleMode.FIT);
        }
    }
    public void setFileName(String name) { //设置文件名并显示出来
        mTitle = name;
        if (mFileName != null)
            mFileName.setText(mTitle);

        mFileName.setGravity(Gravity.CENTER);
    }
    /**
     * 时间戳回调
     */
    private NELivePlayer.OnCurrentSyncTimestampListener mOnCurrentSyncTimestampListener = new NELivePlayer.OnCurrentSyncTimestampListener() {
        @Override
        public void onCurrentSyncTimestamp(long timestamp) {
            Log.v("", "OnCurrentSyncTimestampListener,onCurrentSyncTimestamp:" + timestamp);

        }
    };

    private NELivePlayer.OnCurrentSyncContentListener mOnCurrentSyncContentListener = new NELivePlayer.OnCurrentSyncContentListener() {
        @Override
        public void onCurrentSyncContent(List<String> content) {
            StringBuffer sb = new StringBuffer();
            for (String str : content) {
                sb.append(str + "\r\n");
            }
            toast("onCurrentSyncContent,收到同步信息:" + sb.toString());
            Log.v("", "onCurrentSyncContent,收到同步信息:" + sb.toString());
        }
    };
    /**
     * 处理service后台播放逻辑
     */
    private void intentToStartBackgroundPlay() {
        if (!mHardware && !isPauseInBackgroud) {
            PlayerService.intentToStart(this);
        }
    }
    private void intentToStopBackgroundPlay() {
        if (!mHardware && !isPauseInBackgroud) {
            PlayerService.intentToStop(this);
            player = null;
        }
    }
    private void enterBackgroundPlay() {
        if (!mHardware && !isPauseInBackgroud) {
            PlayerService.setMediaPlayer(player);
        }
    }
    private void stopBackgroundPlay() {
        if (!mHardware && !isPauseInBackgroud) {
            PlayerService.setMediaPlayer(null);
        }
    }
    //处理与电话逻辑
    private Observer<Integer> localPhoneObserver = new Observer<Integer>() {
        @Override
        public void onEvent(Integer phoneState) {
            if (phoneState == TelephonyManager.CALL_STATE_IDLE) {
                player.start();
            } else if (phoneState == TelephonyManager.CALL_STATE_RINGING) {
                player.stop();
            } else {
                Log.i("", "localPhoneObserver onEvent " + phoneState);
            }

        }
    };
    private void start() {

        player.start();
    }
    private VodPlayerObserver playerObserver = new VodPlayerObserver() {
        @Override
        public void onCurrentPlayProgress(long currentPosition, long duration, float percent, long cachedPosition) {

        }

        @Override
        public void onSeekCompleted() {
            mHandler.sendEmptyMessageDelayed(SHOW_PROGRESS, 1000);
        }

        @Override
        public void onCompletion() {
            mPauseButton.setImageResource(R.mipmap.nemediacontroller_pause);
        }

        @Override
        public void onNetStateBad() {

        }

        @Override
        public void onDecryption(int ret) {

        }

        @Override
        public void onPreparing() {

        }

        @Override
        public void onPrepared(MediaInfo info) {
            mediaInfo = info;
        }

        @Override
        public void onError(int code, int extra) {
            mBuffer.setVisibility(View.INVISIBLE);
            if(code == CauseCode.CODE_VIDEO_PARSER_ERROR) {
                toast("视频解析出错");
            }else {
                AlertDialog.Builder build = new AlertDialog.Builder(ReViewTaskActivity.this);
                build.setTitle("播放错误").setMessage("错误码：" + code)
                        .setPositiveButton("确定", null)
                        .setCancelable(false)
                        .show();
            }

        }

        @Override
        public void onFirstVideoRendered() {
            toast("视频第一帧已解析");
        }
        @Override
        public void onFirstAudioRendered() {
//            showToast("音频第一帧已解析");
        }

        @Override
        public void onBufferingStart() {
            mBuffer.setVisibility(View.VISIBLE);
        }

        @Override
        public void onBufferingEnd() {
            mBuffer.setVisibility(View.GONE);
        }
        @Override
        public void onBuffering(int percent) {
            LogUtil.d("", "缓冲中..." + percent + "%");
            mProgressBar.setSecondaryProgress(percent);
        }

        @Override
        public void onHardwareDecoderOpen() {

        }

        @Override
        public void onStateChanged(StateInfo stateInfo) {

        }

        @Override
        public void onParseDefinition(List<NEDefinitionData> data) {
            toast("解析到多个清晰度");
        }
        @Override
        public void onAutoSwitchDefinition(NEDefinitionData.DefinitionType definitionType) {
            toast("自动切换到清晰度" + definitionType);
        }

        @Override
        public void onVideoFrameFilter(NELivePlayer.NEVideoRawData videoRawData) {

        }

        @Override
        public void onAudioFrameFilter(NELivePlayer.NEAudioRawData audioRawData) {

        }

        @Override
        public void onHttpResponseInfo(int code, String header) {
            Log.i("", "onHttpResponseInfo,code:" + code + " header:" + header);
        }
    };
    private SeekBar.OnSeekBarChangeListener mProgressSeekListener = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

        }
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            mHandler.removeMessages(SHOW_PROGRESS);

        }
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            player.seekTo(player.getDuration() * seekBar.getProgress() / 100);
        }
    };
    public void getSnapshot() {
        if (mediaInfo == null) {
            toast("截图不成功");
        } else if (mediaInfo.getVideoDecoderMode().equals("MediaCodec")) {
            toast("截图不支持硬件解码");
        } else {
            Bitmap bitmap = player.getSnapshot();
            String picName = "/sdcard/NESnapshot" + System.currentTimeMillis() + ".jpg";
            File f = new File(picName);
            try {
                f.createNewFile();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            FileOutputStream fOut = null;
            try {
                fOut = new FileOutputStream(f);
                if (picName.substring(picName.lastIndexOf(".") + 1, picName.length()).equals("jpg")) {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
                } else if (picName.substring(picName.lastIndexOf(".") + 1, picName.length()).equals("png")) {
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
                }
                fOut.flush();
                fOut.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            toast("截图成功");
        }
    }
    private View.OnClickListener mSnapShotListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (mMediaType.equals("localaudio") || mHardware) {
                if (mMediaType.equals("localaudio"))
                    toast("音频播放不支持截图！");
                else if (mHardware)
                    toast("硬件解码不支持截图！");
                return;
            }
            getSnapshot();
        }
    };
    private View.OnClickListener mSetPlayerScaleListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if(StringUtils.isNull(mVideoPath)){toast("暂无录播"); return;}
            Bundle bundle = new Bundle();
            bundle.putString("media_type", "videoondemand");
            bundle.putString("decode_type", "software");
            bundle.putString("videoPath", mVideoPath);
            jumpTo(VodActivity.class,bundle);
//            player.setupRenderView(null, VideoScaleMode.NONE);
//            if (mIsFullScreen) {
//                mSetPlayerScaleButton.setImageResource(R.mipmap.nemediacontroller_scale01);
//                mIsFullScreen = false;
//                player.setupRenderView(textureView, VideoScaleMode.FIT);
//
//            } else {
//                mSetPlayerScaleButton.setImageResource(R.mipmap.nemediacontroller_scale02);
//                mIsFullScreen = true;
//                player.setupRenderView(textureView, VideoScaleMode.FULL);
//            }
        }
    };
    @Override
    public void success(String action, BaseBean baseBean) {
        if(baseBean.code == 200) {
            PrePareOrReViewDetailBean bean = (PrePareOrReViewDetailBean) GsonUtils.getInstance(this).parseComplexJArrayByCommon(baseBean, PrePareOrReViewDetailBean.class);
            mVideoPath = bean.video;
            cours_list = bean.courseware;
            work_list.clear();
            if(bean.task!=null){
                work_list.addAll(bean.task);
            }
            if(bean.task2!=null){
                work_list.addAll(bean.task2);
            }
            coursewareAdapter.setNewData(cours_list);
            workAdapter.setNewData(work_list);
            initdata(bean);
        }
    }

    @Override
    public void error(String action, Throwable e) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_reviewtask;
    }

    @Override
    protected void findViews() {
        //-----视频点播
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); //保持屏幕常亮
        PhoneCallStateObserver.getInstance().observeLocalPhoneObserver(localPhoneObserver, true);
        tv_subject = getView(R.id.tv_subject);
        tv_teacher = getView(R.id.tv_teacher);
        tv_date_time_week = getView(R.id.tv_date_time_week);
        rc_cours = getView(R.id.rcly_coursave);
        //rc_note = getView(R.id.rcly_note);
        rc_work = getView(R.id.rcly_work);
    }
    private void initView() {
        //这里支持使用SurfaceView和TextureView
        //surfaceView = findViewById(R.id.live_surface);
        textureView = (AdvanceSingleTextureView) findViewById(R.id.live_texture);
        mPlayToolbar = (RelativeLayout) findViewById(R.id.play_toolbar);
        mPlayToolbar.setVisibility(View.GONE);
        mPlayBack = (ImageButton) findViewById(R.id.player_exit);//退出播放
        mPlayBack.getBackground().setAlpha(0);
        mFileName = (TextView) findViewById(R.id.file_name);
        if (mUri != null) { //获取文件名，不包括地址
            List<String> paths = mUri.getPathSegments();
            String name = paths == null || paths.isEmpty() ? "null" : paths.get(paths.size() - 1);
            setFileName(name);
        }
        mAudioRemind = (ImageView) findViewById(R.id.audio_remind);
        if (mMediaType != null && mMediaType.equals("localaudio")) {
            mAudioRemind.setVisibility(View.VISIBLE);
        } else {
            mAudioRemind.setVisibility(View.INVISIBLE);
        }
        mBuffer = findViewById(R.id.buffering_prompt);
        mPauseButton = (ImageView) findViewById(R.id.mediacontroller_play_pause); //播放暂停按钮
        mPauseButton.setImageResource(R.mipmap.nemediacontroller_pause);
        mPauseButton.setOnClickListener(mPauseListener);
        mPlayBack.setOnClickListener(mPlayBackOnClickListener); //监听退出播放的事件响应
        mSetPlayerScaleButton = (ImageView) findViewById(R.id.video_player_scale);  //画面显示模式按钮
        mSnapshotButton = (ImageView) findViewById(R.id.snapShot);  //截图按钮
        mMuteButton = (ImageView) findViewById(R.id.video_player_mute);  //静音按钮
        mMuteButton.setOnClickListener(mMuteListener);
        mProgressBar = (SeekBar) findViewById(R.id.mediacontroller_seekbar);  //进度条
        mProgressBar.setOnSeekBarChangeListener(mProgressSeekListener);
        mEndTime = (TextView) findViewById(R.id.mediacontroller_time_total); //总时长
        mEndTime.setText("--:--:--");
        mCurrentTime = (TextView) findViewById(R.id.mediacontroller_time_current); //当前播放位置
        mCurrentTime.setText("--:--:--");
        mHandler.sendEmptyMessage(SHOW_PROGRESS);
        mSnapshotButton = (ImageView) findViewById(R.id.snapShot);  //截图按钮
        mSnapshotButton.setOnClickListener(mSnapShotListener);
        mSetPlayerScaleButton = (ImageView) findViewById(R.id.video_player_scale);  //画面显示模式按钮
        mSetPlayerScaleButton.setOnClickListener(mSetPlayerScaleListener);


    }
    @Override
    protected void formatViews() {
        //创建布局管理
        rc_cours.setLayoutManager(new MyLayoutManager(this,LinearLayoutManager.VERTICAL,false));
       // rc_note.setLayoutManager(new MyLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        rc_work.setLayoutManager(new MyLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        coursewareAdapter = new PrePareTaskCoursewareAdapter(this,R.layout.item_cours_list,cours_list);
        coursewareAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("url",cours_list.get(position).link);
                bundle.putInt("type",cours_list.get(position).courseware_type);
                jumpTo(CoursewareDetailsActivity.class,bundle);
            }
        });
       // noteAdapter = new PrePareTaskNoteAdapter(this,R.layout.item_note_list,note_list);
        workAdapter = new PrePareTaskWorkAdapter(this,R.layout.item_work_list,work_list);
        rc_cours.setAdapter(coursewareAdapter);
       // rc_note.setAdapter(noteAdapter);
        rc_work.setAdapter(workAdapter);
        workAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()){
                    case R.id.bt_answer:
                        Button button = (Button) view;
                        if(work_list.size()<=0){return;}
                        if(button.getText().toString().equals("答题")){
                            Bundle bundle = new Bundle();
                            bundle.putInt("task_id",work_list.get(position).task_id);
                            bundle.putInt("paper_id",work_list.get(position).paper_id);
                            bundle.putInt("student_task_id",work_list.get(position).student_task_id);
                            bundle.putString("title",tv_subject.getText().toString()+"作业");
                            if(work_list.get(position).paper_type == 3){
                                jumpTo(DoTheImageWorkActivity.class,0,bundle);
                            }else {
                                jumpTo(DoTheWorkActivity.class,0,bundle);
                            }
                        }else {
                            Bundle bundle = new Bundle();
                           // bundle.putInt("task_id",work_list.get(position).task_id);
                            bundle.putInt("answer_id",work_list.get(position).answer_id);
                            bundle.putInt("student_task_id",work_list.get(position).student_task_id);
                            jumpTo(AnswerSheetActivity.class,0,bundle);
                        }

                        break;
                }
            }
        });
    }

    @Override
    protected void formatData() {
        initView();
        initPlayer();
        player.registerPlayerObserver(playerObserver, true);
//        for(int i=0;i<3;i++){
//            ItemBean bean = new ItemBean();
//            bean.setImgurl(""+i);
//            bean.setStr("人教版高中信息技术选修1");
//            PrePareTaskWorkBean workBean = new PrePareTaskWorkBean();
//            cours_list.add(bean);
//            note_list.add(bean);
//            work_list.add(workBean);
//        }
        loaddata();
    }
    private void loaddata(){
        Map<String, String> map = new HashMap<>();
        map.put("room_id",""+room_id);
        post("schedule/getCourseware", map, GetSubjectBean.class, false);
    }
    private  void initdata(PrePareOrReViewDetailBean bean){
        tv_date_time_week.setText(""+bean.room_date+"  "+bean.start_time+"---"+bean.end_time+"("+bean.week+")");
        tv_subject.setText(bean.room_name);
        tv_teacher.setText(bean.real_name);
//        tv_teachinggoal.setText(bean.objective);
//        tv_teachingmaterials.setText(bean.nodus);

    }
    @Override
    protected void getBundle(Bundle bundle) {
        room_id = bundle.getInt("room_id");
    }
//    String url = "http://ohjdda8lm.bkt.clouddn.com/course/sample1.mp4";
    @Override
    public void onClick(View view) {
        switch (view.getId()){
//            case R.id.video_view:
//                //http://vjs.zencdn.net/v/oceans.mp4
//
//                break;
//            case R.id.img_start_or_pause:
//
//                break;
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        loaddata();
        if (player != null && !mPaused) {
            player.onActivityResume(false);
        }
    }
    @Override
    protected void onStop() {
        super.onStop();
        enterBackgroundPlay();
        if (player != null) {
            player.onActivityStop(false);
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        releasePlayer();
    }
    private View.OnClickListener mPauseListener = new View.OnClickListener() {
        public void onClick(View v) {
            if (player.isPlaying()) {
                mPauseButton.setImageResource(R.mipmap.nemediacontroller_pause);
                toast("暂停播放");
                player.pause();
                mPaused = true;
            } else {
                if(StringUtils.isNull(mVideoPath)){toast("暂无录播"); return;}
                mPauseButton.setImageResource(R.mipmap.nemediacontroller_play);
                toast("继续播放");
                player.start();
                mPaused = false;
            }
        }
    };

    private View.OnClickListener mMuteListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (!isMute) {
                mMuteButton.setImageResource(R.mipmap.nemediacontroller_mute01);
                player.setMute(true);
                isMute = true;
            } else {
                mMuteButton.setImageResource(R.mipmap.nemediacontroller_mute02);
                player.setMute(false);
                isMute = false;
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        loaddata();
    }
}
